package com.ng.framework.view.desktop.table;

import java.awt.Component;

import javax.swing.DefaultCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

import com.ng.framework.util.NGUtil;

public class NGFractionCellEditor extends DefaultCellEditor {

	private static final long serialVersionUID = -8297693617131564286L;

	public NGFractionCellEditor() {
		super(new JTextField());
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		final JTextField editor = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);

		if (value instanceof Double) {
			editor.setHorizontalAlignment(SwingConstants.RIGHT);
			editor.setText(NGUtil.doubleToFraction((Double) value, true));

			editor.selectAll();

			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					editor.requestFocus();

					SwingUtilities.invokeLater(new Runnable() {
						public void run() {
							editor.setCaretPosition(editor.getText().length());
						}
					});
				}
			});
		}
		return editor;
	}

	@Override
	public boolean stopCellEditing() {
		try {
			this.getCellEditorValue();
			return super.stopCellEditing();
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}

	}

	@Override
	public Object getCellEditorValue() {
		Double value = null;
		String s = (String) super.getCellEditorValue();

		try {
			value = Double.parseDouble(s);
		} catch (NumberFormatException e) {
			value = NGUtil.fractionToDouble(s);
		}

		return value;
	}

}
